var app = getApp();
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var WxParse = require('../wxParse/wxParse.js');

Page({
  data: {
    cartCounts: 0,
    swiperpics: [],
    product: null,
    productStock: null,
    couponTypeList: [],
    isSell: false,
    sellDate: '',
    isSpec: 0,
    specValueList: [],
    specNameValue: [],
    productStockId: '',
    countDownDay: 0,//倒计时 天数
    countDownHour: 0,//倒计时 时
    countDownMinute: 0,//分
    countDownSecond: 0,//秒
    id: 0,
    goods: {},
    gallery: [],
    attribute: [{
      name:'颜色',
      value:'黄色、粉色、黑色'
    },{
      name:'面料',
      value:'纯棉'
    },{
      name:'清洗方式',
      value:'手洗、机洗'
    }],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    openCoupons:false,
    boxShow: false,

    openShare: false,
    openToshare: false,

    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png"
  },
  onLoad: function (options) {
    this.setData({
      productStockId: options.productStockId
    });
    this.getProductDetail();
    this.getAssess();
  },
  //点击立即购买
  toBuy: function (event) {
    var that = this;
    var clickType = event.currentTarget.dataset.nameId;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    } else {
      util.request(api.CheckImproveUrl, {}, 'POST').then(function (data) {
        if (data.type == 'success') {
          var isImprove = data.data.isImprove;
          if (isImprove == 0) {
            wx.navigateTo({
              url: '/pages/ucenter/improveinfo/improveinfo',
            })
          } else {
            var memo = that.data.grouping.memo;
            if (memo != '活动进行中') {
              util.showErrorToast(memo);
              return false;
            }
            var productStockId = that.data.productStockId;
            var quantity = that.data.number;
            var price = that.data.grouping.price;
            var imgUrl = that.data.product.showUrl;
            var name = that.data.product.name;
            var subName = that.data.product.subname;
            var specName = that.data.productStock.specName;
            var memo = that.data.product.memo;
            var groupId = that.data.grouping.groupId;
						var isPointPay = that.data.product.isPointPay;
            wx.navigateTo({
							url: '/pages/shopping/checkoutGroup/checkoutGroup?productStockId=' + productStockId + '&quantity=' + quantity + '&price=' + price + '&imgUrl=' + imgUrl + '&name=' + name + '&subName=' + subName + '&specName=' + specName + '&memo=' + memo + '&groupId=' + groupId + '&isPointPay=' + isPointPay
            })
          }
        }
      });
    }
  },
  //获取团购商品详情
  getProductDetail: function () {
    var that = this;
    var data = {
      productStockId: this.data.productStockId
    }
    util.request(api.GroupingProductDetail, data, 'get').then(function (data) {
      if (data.type === 'success') {
        var lastSecond = data.data.grouping.lastSecond;
        that.cutDown(lastSecond);
        that.setData({
          swiperpics: data.data.swiperpics,
          product: data.data.product,
          productStock: data.data.productStock,
          isSell: data.data.isSell,
          sellDate: data.data.sellDate,
          grouping: data.data.grouping,
          shippingFee: data.data.shippingFee
        });
        WxParse.wxParse('content', 'html', data.data.product.content, that, 0);
      } else {
        console.log(data.data.content);
        wx.navigateBack();
      }
    });
  },
  //倒计时
  cutDown: function (lastSecond) {
    var totalSecond = lastSecond;

    var interval = setInterval(function () {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        util.showErrorToast('活动已结束');
        var grouping = this.data.grouping;
        grouping.memo = '活动已结束'
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          grouping: grouping
        });
      }
    }.bind(this), 1000);
  },
  //减少数量
  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  //增加数量
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },
  //查看全部评价
  viewAll: function () {
    var productStockId = this.data.productStockId;
    wx.navigateTo({
      url: '/pages/comment/comment?productStockId=' + productStockId,
    })
  },
  //获取第一条评价
  getAssess: function () {
    var that = this;
    var data = {
      productStockId: this.data.productStockId
    }
    util.request(api.PinglunFirst, data, 'POST').then(function (data) {
      if (data.type === 'success') {
        that.setData({
          assess: data.data.assess,
          assessImgList: data.data.assessImgList,
          assessCounts: data.data.assessCounts,
          assessName: data.data.assessName,
          assessAvatar: data.data.assessAvatar,
          assessTime: data.data.assessTime
        });
      } else {
        console.log(data.content);
      }
    });
  },
  closeAttrOrCollect: function () {
    let that = this;
    if (this.data.openAttr) {
      this.setData({
        openAttr: false,
        boxShow: false,
      });
      if (that.data.userHasCollect == 1) {
        that.setData({
          'collectBackImage': that.data.hasCollectImage
        });
      } else {
        that.setData({
          'collectBackImage': that.data.noCollectImage
        });
      }
    } else {
      //添加或是取消收藏
      util.request(api.CollectAddOrDelete, { typeId: 0, valueId: this.data.id }, "POST")
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            if (_res.data.type == 'add') {
              that.setData({
                'collectBackImage': that.data.hasCollectImage
              });
            } else {
              that.setData({
                'collectBackImage': that.data.noCollectImage
              });
            }

          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });
    }
  },











  //分享
  toShare: function (e) {
    if (this.data.openToshare == false) {
      this.setData({
        openToshare: !this.data.openToshare,
      });
    }
  },
  //关闭分享弹窗
  closeShare: function () {
    this.setData({
      openToshare: false,
    });
  },

  //分享图片
  sharePic: function (e) {
    if (this.data.openShare == false) {
      this.setData({
        openShare: !this.data.openShare,
        openToshare: !this.data.openToshare,
      });
    }
  },

  //关闭分享图片弹窗
  closeSharepic: function () {
    this.setData({
      openShare: false,
    });
  },

  bindGetSharePic: function () {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    });
    this.setData({
      openToshare: false
    });
    util.request(api.SharePic, { productStockId: that.data.productStockId, "priceType":"tuangou" }, 'POST').then(function (data) {
      if (data.type == 'success') {
        that.setData({
          openShare: true,
          sharePic: data.data.path
        });
        wx.hideLoading();
      }
    });
  },
  bindCloseSharePic: function () {
    this.setData({
      openShare: false
    });
  },
  bindCloseShareButton: function () {
    this.setData({
      openToshare: false
    });
  },
  bindSaveSharePic: function () {

    wx.downloadFile({
      url: this.data.sharePic,
      success: function (res) {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                title: '保存图片成功！',
              })
            },
            fail(res) {
              wx.showToast({
                title: '保存图片失败！',
              })
            }
          })
        }
      }
    });

  },
  onShareAppMessage: function () {
    var that = this;
    var mid = wx.getStorageSync("memberId");
    if (!mid) {
      mid = "";
    }
    console.log("分享memberId：" + mid);
    return {
      title: '月亮湾商城',
      path: 'pages/index2/index2?recommendId=' + mid + "&productStockId=" + that.data.productStockId + "&page=tuangou"
    }
  }

})